package com.ano.controller;

import com.ano.entity.Cluster;
import com.ano.service.ClusterService;
import com.ano.utils.JWTUtil;
import com.ano.utils.ResultUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("cluster")
public class ClusterController {

    @Autowired
    ClusterService clusterService;

    /**
     * 查询，一页显示六个簇
     * 返回的格式如下
     * {
     *     "msg": "查询成功！！！",
     *     "state": true,
     *     "token": null,
     *     "obj": {
     *         "total": 5,
     *         "list": [
     *             {
     *                 "id": "123",
     *                 "clustername": "www",
     *                 "hostid": "496048a1-6653-41ca-9a6b-41f4ab41ff79",
     *                 "createtime": "2020-11-06",
     *                 "clustermark": "",
     *                 "note": null,
     *                 "cluimg": null
     *             }
     *         ],
     *         "pageNum": 1,
     *         "pageSize": 1,
     *         "size": 1,
     *         "startRow": 1,
     *         "endRow": 1,
     *         "pages": 5,
     *     }
     * }
     * 有些不太重要的就删除了
     * 如果前端要取用其中的第一个cluster的id:  res.data.obj.list[0].id
     * @param num
     * @param size
     * @param clustername
     * @param typename
     * @return
     */
    @PostMapping("query")
    @ResponseBody
    public ResultUtil<PageInfo<Cluster>> query(@RequestParam(value = "num",defaultValue = "1") Integer num,
                                                @RequestParam(value = "size",defaultValue = "6")Integer size,
                                                @RequestParam(value = "clustername",defaultValue = "") String clustername,
                                                @RequestParam(value = "typename",defaultValue = "") String typename){
        ResultUtil<PageInfo<Cluster>> res = new ResultUtil<PageInfo<Cluster>>();
        PageInfo<Cluster> clusterInfo = new PageInfo<Cluster>();
        System.out.println("开始查询！！！");
        try {
            //如果clustername和typename为空就查询所有
            if("".equals(clustername)&&"".equals(typename)){
                clusterInfo = clusterService.findAllForPage(num, size);
                res.setMsg("查找全部成功！！！").setObj(clusterInfo);
            }else{
                if("".equals(clustername)){
                    //如果是clustername为空，则按type查找
                    clusterInfo = clusterService.findByTypeForPage(num,size,typename);
                    res.setMsg("按类型查找成功！！！").setObj(clusterInfo);
                }else if("".equals(typename)){
                    //如果type为空，按名字查找
                    clusterInfo = clusterService.findByNameForPage(num,size,clustername);
                    res.setMsg("按名字查找成功！！！").setObj(clusterInfo);
                }else {
                    //都不为空，则一起一起查找
                    clusterInfo = clusterService.findByNameAndTypeForPage(num, size, clustername, typename);
                    res.setMsg("按名字和类型查找成功！！！").setObj(clusterInfo);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 通过id或者clustername查找，如果其中一个为空就查找另一个
     * 如果两个都为空就查找全部
     * 如果两个都不为空就通过id查找
     * @param id
     * @param clustername
     * @return
     */
    @ResponseBody
    @PostMapping("find")
    public ResultUtil<List<Cluster>> findByIdOrName(@RequestParam(value = "id",defaultValue = "") String id,
                                              @RequestParam(value = "clustername",defaultValue = "") String clustername){

        ResultUtil<List<Cluster>> res = new ResultUtil<List<Cluster>>();
        List<Cluster> clusters = new ArrayList<Cluster>();
        try {
            if("".equals(id)&&"".equals(clustername)){
                //如果都为空，就查询全部
                clusters = clusterService.findAll();
                res.setMsg("查询全部成功！！！").setObj(clusters);
            }else {
                if("".equals(id)){
                    //如果id是空就按clustername查询
                    Cluster cluster = clusterService.findByFullName(clustername);
                    //加入一个List
                    clusters.add(cluster);
                    res.setMsg("通过名字查询成功！！！").setObj(clusters);
                }else if("".equals(clustername)) {
                    //如果clustername为空就用id去查找
                    Cluster cluster = clusterService.findById(id);
                    clusters.add(cluster);
                    res.setMsg("通过id查询成功！！！").setObj(clusters);
                }else {
                    //如果都不为空，则按id查询
                    Cluster cluster = clusterService.findById(id);
                    clusters.add(cluster);
                    res.setMsg("通过id查询成功！！！").setObj(clusters);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;

    }


    @ResponseBody
    @RequestMapping("findByHostId")
    public ResultUtil<List<Cluster>> findByHostId(@RequestParam("token") String token){
        ResultUtil<List<Cluster>> res = new ResultUtil<List<Cluster>>();
        try{
            DecodedJWT verify = JWTUtil.verify(token);
            String hostid = verify.getClaim("id").asString();
            List<Cluster> clusters = clusterService.findByHostId(hostid);
            res.setMsg("查询成功！！！").setObj(clusters);
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }
        return res;
    }

    /**
     * 获取簇信息以及token
     * token用于将id和username存入cluster
     * 返回不用返回对象
     * 不知道为什么这个RequestParam必须加
     * @param cluster
     * @param token
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public ResultUtil add(Cluster cluster,String token,@RequestParam("typenames") List<String> typenames){
        ResultUtil res = new ResultUtil();
        for (String typename : typenames) {
            System.out.println(typename);
        }
        try{
            //先取出id和username
            DecodedJWT verify = JWTUtil.verify(token);
            String hostid = verify.getClaim("id").asString();
            String hostname = verify.getClaim("username").asString();
            cluster.setHostid(hostid);
            cluster.setHostname(hostname);
            clusterService.add(cluster,typenames);
            res.setMsg("簇创建成功！！！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (JWTDecodeException e){
            e.printStackTrace();
            res.setState(false).setMsg("token wrong");
        }catch (Exception e){
            e.printStackTrace();
            res.setState(false).setMsg(e.getMessage());
        }
        return res;
    }

    /**
     * 传入cluster的id，进行删除
     * @param clustername
     * @return
     */
    @PostMapping("delete")
    @ResponseBody
    public ResultUtil delete(String clustername){
        ResultUtil res = new ResultUtil();
        try{
            Cluster cluster = clusterService.findByFullName(clustername);
            clusterService.delete(cluster.getId());
            res.setMsg("删除成功！！！");
        }catch (Exception e){
            e.printStackTrace();
            res.setMsg("删除失败！！！").setState(false);
        }
        return res;
    }

    @PostMapping("update")
    @ResponseBody
    public ResultUtil update(Cluster cluster,@RequestParam("typenames") List<String> typenames){
        ResultUtil res = new ResultUtil();

        try{
            Cluster findCluster = clusterService.findByFullName(cluster.getClustername());
            cluster.setHostname(findCluster.getHostname());
            cluster.setHostid(findCluster.getHostid());
            cluster.setId(findCluster.getId());
            cluster.setClustername(findCluster.getClustername());
            clusterService.update(cluster,typenames);
            res.setMsg("更新成功！！！");
        }catch (Exception e){
            e.printStackTrace();
            res.setMsg("更新失败！！！").setState(false);
        }
        return res;
    }

    /**
     * 传入n个cluster的id，遍历查找其对应的types
     * @param clusids
     * @return
     */
    @PostMapping("findTypes")
    @ResponseBody
    public ResultUtil findTypes(@RequestParam("clusids") List<String> clusids){
        ResultUtil res = new ResultUtil();
        try {
            List<List<String>> typesList = new ArrayList<>();
            for (String clusid : clusids) {
                List<String> findTypes = clusterService.findTypesByClusId(clusid);
                typesList.add(findTypes);
            }
            res.setMsg("查找类型成功！！！").setObj(typesList);
        } catch (Exception e) {
            e.printStackTrace();
            res.setMsg("查找类型失败！！！").setState(false);
        }
        return res;
    }
}
